package com.wx.handler.security;

import cn.hutool.json.JSONUtil;
import com.wx.common.SecurityUser;
import com.wx.common.WrapMapper;
import com.wx.common.Wrapper;
import com.wx.constants.RedisKeyPrefix;
import com.wx.service.RedisService;
import com.wx.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <p>Title:      CustomerAuthenticationSuccessHandler. </p>
 * <p>Description 认证成功处理器 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author         <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since      2020/9/18 20:32
 */
@Slf4j
@Component("customerAuthenticationSuccessHandler")
public class CustomerAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 用uuid来做token
        String token = UUID.randomUUID().toString();
        // 将用户信息存入redis中
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        redisService.set(RedisKeyPrefix.ONLINEUSER+token, JSONUtil.toJsonStr(securityUser),RedisKeyPrefix.USER_EXPIRE_TIME_MINUTE);
        ResponseUtil.write(response, WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, token));
    }
}
